package controllers.payapi;

import activity.give.GiveActivitySpecProduct;
import address.Address;
import com.pingplusplus.model.Charge;
import com.pingplusplus.model.RedEnvelope;
import coupon.DiscountCouponDetailHistory;
import enums.OrderItemType;
import enums.PaymentType;
import helper.EmayHelper;
import helper.PingppHelper;
import jodd.util.StringUtil;
import models.weixin.WebUser;
import models.weixin.WeixinRedBao;
import models.weixin.amount.WebUserAccount;
import models.weixin.amount.WebUserAccountHistory;
import order.*;
import org.apache.commons.lang.StringUtils;
import play.Logger;
import play.jobs.Job;
import play.mvc.Controller;
import product.enums.ProductAttribute;
import product.merchant.ProductSpecMerchant;
import util.common.DateUtil;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 支付回调.
 */
public class PaymentPayCallback extends Controller {

//    public static void execute() {
//        String body = IO.readContentAsString(request.body);
//        Logger.info("LOG02450: get PaymentCallback body=" + body);
////        Event event = new Gson().fromJson(body , Event.class);
//        if(body == null) {
//            Logger.info("LOG02451: get PaymentCallback body is Null");
//            return;
//        }
//        JSONObject jsonObject = new JSONObject(body);
//        if(jsonObject == null) {
//            Logger.info("LOG02452: get PaymentCallback jsonObject is Null");
//            return;
//        }
//        String type = jsonObject.getString("type");
//        if(StringUtil.isBlank(type) || !type.equals("charge.succeeded")) {
//            Logger.info("LOG02453: get PaymentCallback jsonObject.type is Null 或者 type is : %s" , type);
//            return;
//        }
//
//        JSONObject dataObject = jsonObject.getJSONObject("data");
//        if(dataObject == null) {
//            Logger.info("LOG02454: get PaymentCallback dataObject is Null");
//            return;
//        }
//        JSONObject orderObject = dataObject.getJSONObject("object");
//        if(orderObject == null) {
//            Logger.info("LOG02455: get PaymentCallback orderObject is Null");
//            return ;
//        }
//
//        String orderNo = orderObject.getString("order_no");
//        if(orderNo == null) {
//            Logger.info("LOG02456: get PaymentCallback orderNo is Null");
//            return;
//        }
//
//        Order order = Order.findByOrderNumber(orderNo);
//        Logger.info("OrderNumber : %s" , orderNo);
////            if(order != null && order.status == OrderStatus.UNPAID) {
//        if(order != null && order.status == OrderStatus.UNPAID) {
//            // 修改订单状态
//            OrderBuilder.orderNumber(order.orderNumber).changeToPaid();
//
//            // 设置订单支付方式
//            setPaymentType(PaymentType.WEIXIN_PUB , order);
//
//            //Redis 更新数量  并且设置购物车
//            updateRedisProduct(order);
//
//            // 设定 分享朋友圈后, 朋友圈用户下单  . 分享人 可获得红包
////                if(order.merchant != null && order.merchant.haveShareRedBao != null && order.merchant.haveShareRedBao) {
////                    sendShareRedBao(order);
////                }
//
//            // 如果是充值卡  则 金额充值到账户中
//            checkToAccount(order);
//
//            // 如果有代金券赠送政策  则赠送代金券
//            DiscountCoupon.checkToCoupon(order);
//
//            //用户消费成功 减少代金券
//            checkReduceCoupon(order);
//
//
//            checkGiveSpecProduct(order);
//
//
//            //修改库存
//            changeProductNumber(order);
//
//
//
//            //发送短信通知
////                sendPhoneMsg(order, itemName);
//            ok();
//        } else {
//            Logger.info("LOG 990001 PaymentCallBack Error : %s 订单状态为: %s  原因:订单不存在 或 该订单状态不是未支付状态. " , order.orderNumber , order.status);
//            error();
//        }



//
//
//
//
//        Event event = Webhooks.eventParse(body);
//
//        Logger.info("LOG02490: eventType=" + event.getType() + ", object=" + event.getObject() + "TEST : " + event.getType().equals("red_envelope.sent"));
//        // ping++没有按文档中说明一样带入签名.
//        for (String key : request.headers.keySet()) {
//            Logger.info("LOG02480: key=" + key + ", header=" + request.headers.get(key).value());
//        }
//        //Http.Header headerSignature = request.headers.get("x-pingplusplus-signature");
//        //Logger.info("LOG02470: signature=" + headerSignature.value());
//
////        Logger.info("LOG02481 : Event =" + event);
//
//        Object obj = Webhooks.parseEvnet(event.toString());
//        if (obj instanceof Charge) {
//            Logger.debug("webhooks 发送了 Charge");
//            Charge charge = (Charge) obj;
//            Order order = Order.findByOrderNumber(charge.getOrderNo());
//            Logger.info("OrderNumber : %s" , charge.getOrderNo());
////            if(order != null && order.status == OrderStatus.UNPAID) {
//            if(order != null && order.status == OrderStatus.UNPAID) {
//                // 修改订单状态
//                OrderBuilder.orderNumber(order.orderNumber).changeToPaid();
//
//                // 设置订单支付方式
//                setPaymentType(charge , order);
//
//                //Redis 更新数量  并且设置购物车
//                updateRedisProduct(order);
//
//                // 设定 分享朋友圈后, 朋友圈用户下单  . 分享人 可获得红包
////                if(order.merchant != null && order.merchant.haveShareRedBao != null && order.merchant.haveShareRedBao) {
////                    sendShareRedBao(order);
////                }
//
//                // 如果是充值卡  则 金额充值到账户中
//                checkToAccount(order);
//
//                // 如果有代金券赠送政策  则赠送代金券
//                DiscountCoupon.checkToCoupon(order);
//
//                //用户消费成功 减少代金券
//                checkReduceCoupon(order);
//
//
//                checkGiveSpecProduct(order);
//
//
//                //修改库存
//                changeProductNumber(order);
//
//                //发送短信通知
////                sendPhoneMsg(order, itemName);
//                ok();
//            } else {
//                Logger.info("LOG 990001 PaymentCallBack Error : %s 订单状态为: %s  原因:订单不存在 或 该订单状态不是未支付状态. " , order.orderNumber , order.status);
//                error();
//            }
//
//
//        } else if (obj instanceof Refund) {
//
//        } else if (obj instanceof Summary) {
//            Logger.debug("webhooks 发送了 Summary");
//        } else if (event.getType().equals("red_envelope.sent")) {
//        }
//        Logger.info("LOG02540: 不能处理的请求, 放弃.");
//        ok();
//    }


//    private static void updateRedisProduct(Order order) {
//        List<OrderItem> orderItems = OrderItem.getListByOrder(order);
//        List<ShopCart> shopCartList = ShopCart.findShopCartByUserAndMerchant(order.webUser, order.merchant.id);
//        for(OrderItem oi : orderItems) {
//            ProductSpecMerchant psm = OrderItem.getProductSpecMerchantByOrderItem(oi);
//            for(ShopCart shopCart : shopCartList) {
//                //修改购物车信息
//                if(oi.goods == shopCart.goods) {
//                    shopCart.deleted = DeletedStatus.DELETED;
//                    shopCart.status = ShopCartStatus.BUY;
//                    shopCart.save();
//                }
//            }
//            ProductSpecMerchant.subtractRedis(psm , oi.buyNumber);
//        }
//
//        //更新购物车缓存数量
//        Long shopcartCount = ShopCart.findShopCartSize(order.webUser,order.merchant.id);
//        CacheHelper.objectToCache(ShopCart.CACHE_SHOP_CART_COUNT + order.webUser.id + "_" + order.merchant.id , shopcartCount.toString());
//    }



    /**
     * 修改库存
     * @param order
     * @return
     */
    private static String changeProductNumber(Order order) {
        List<OrderItem> orderItems = OrderItem.getListByOrder(order);
        StringBuffer itemNames = new StringBuffer();
        for(OrderItem orderItem : orderItems) {
            itemNames.append("\n商品名称: " + orderItem.goods.name +  "  金额: " + orderItem.salePrice+ " 数量:" + orderItem.buyNumber+ ";");
            //更新商品库存数量
            ProductSpecMerchant psm = ProductSpecMerchant.findById(orderItem.goods.serialId);
            Logger.info("更新前库存:%s",psm.stock);
            psm.stock = psm.stock - orderItem.buyNumber;
            Logger.info("更新后库存:%s",psm.stock);
            psm.save();
        }
        return itemNames.toString();
    }



    private static void sendPhoneMsg(Order order , String itemNames) {
        Address address = order.address;
        String riseName = "社区家园";
        if(order.merchant != null) {
            riseName = order.merchant.name;
        }
        //短信发送
        EmayHelper.sendMsg(address.phone, "\n客户" + order.webUser.nickName + ":终于等到你了！\n您手机为:" + address.phone + "\n于" + DateUtil.dateToString(order.payedAt, "MM月dd日 HH时mm分ss秒") + "\n购买商品:" + itemNames + "\n总计：" + order.paymentedAmount + "元（含运费）\n已出库发货，正在向您奔来;\n 请关注 [" + riseName + "] 查看订单详情");

        //给公司内部人员发短信
//        List<MerchantMessage> merchantMessageList = MerchantMessage.findMerchantMessage(order.feeMerchant.id);
//        Logger.info("merchantMessageList :%s",merchantMessageList.size());
//        if(merchantMessageList != null || merchantMessageList.size() > 0){
//            for (MerchantMessage message : merchantMessageList) {
//                templateMessage(orderUser , message);
////                EmayHelper.sendMsg(message.phone, "亲"+riseName+"又来单了 \n顾客称谓:" + orderUser.name + "\n联系电话：" + orderUser.phone + "\n收货地址：" + orderUser.address + itemNames + "\n客户备注" + (StringUtils.isBlank(orderUser.remark) ? "无" : orderUser.remark));
//            }
//        }else {
//            EmayHelper.sendMsg(order.feeMerchant.phone, "亲"+riseName+"又来单了 \n顾客称谓:" + orderUser.name + "\n联系电话：" + orderUser.phone + "\n收货地址：" + orderUser.address + itemNames + "\n客户备注" + (StringUtils.isBlank(orderUser.remark) ? "无" : orderUser.remark));
//        }
        Logger.info("短信发送成功");
    }




    /**
     * 检测产品是否为  充值卡 。 如果为充值卡。 钱充值到 个人帐户中
     * @param order
     */
    private static void checkToAccount(Order order) {
        //查看个人微信账户
        WebUserAccount account = WebUserAccount.findByWebUser(order.webUser);
        // 如果微信账户为空 创建一个微信账户
        if(account == null) {
            account = new WebUserAccount(order.webUser , 0d).save();
        }
        // 查询订单商品类目
        List<OrderItem> orderItems = OrderItem.findByOrder(order);
        for(OrderItem orderItem : orderItems) {
            // 订单商品对应到 商户商品
            ProductSpecMerchant specMerchant = ProductSpecMerchant.findById(orderItem.goods.serialId);
            if(specMerchant != null && specMerchant.productSpec.product != null) {
                if(specMerchant.productSpec.product.type != null && specMerchant.productSpec.product.type == ProductAttribute.RECHARGEABLE_CARD) {
                     // 修改个人中心账户金额
                     account.amount +=  (specMerchant.productSpec.amount + specMerchant.productSpec.giveAmount);
                     account.save();
                    new WebUserAccountHistory(account , specMerchant.productSpec.amount , specMerchant.productSpec.giveAmount , "用户购买:" +specMerchant.productSpec.product.name + "。型号为:" + specMerchant.productSpec.unit).save();
                }
            }
        }
    }


    /**
     * 用户消费成功  减少代金券
     * @param order
     */
    private static void checkReduceCoupon(Order order) {
        List<OrderPayment> orderPaymentList = OrderPayment.findByOrder(order);
        for(OrderPayment orderPayment : orderPaymentList) {
            orderPayment.discountCouponDetail.amount = orderPayment.discountCouponDetail.amount - orderPayment.amount;
            orderPayment.discountCouponDetail.modifyAt = new Date();
            orderPayment.discountCouponDetail.save();

            new DiscountCouponDetailHistory(orderPayment.discountCouponDetail , orderPayment.amount , "消费于订单:" + order.orderNumber).save();
        }
//        WebUserCoupon webUserCoupon = WebUserCoupon.findByWebUser(order.webUser);
//        if(webUserCoupon != null && order.discountPay != null && order.discountPay > 0) {
//            if(webUserCoupon.amount > order.discountPay) {
//                new WebUserCouponHistory(webUserCoupon , "订单:" + order.orderNumber + "消费代金券" , order.discountPay * (-1)).save();
//                webUserCoupon.amount = webUserCoupon.amount - order.discountPay;
//                webUserCoupon.save();
//            } else {
//                new WebUserCouponHistory(webUserCoupon , "订单:" + order.orderNumber + "消费代金券 | 卡券金额小于订单折扣金额  卡券金额: " + webUserCoupon.amount + "订单折扣金额:" + order.discountPay , order.discountPay * (-1)).save();
//                webUserCoupon.amount = 0d;
//                webUserCoupon.save();
//            }
//
//        }
    }


    /**
     * 设置订单支付方式
     * @param charge
     * @param order
     */
    private static void setPaymentType(Charge charge , Order order) {
        if(charge != null && StringUtils.isNotBlank(charge.getChannel())) {
            String channel = charge.getChannel();
            if(channel.equals("alipay_pc_direct")) {
                order.paymentType = PaymentType.ALI_PC_DIRECT;
            }
            if(channel.equals("wx_pub")) {
                order.paymentType = PaymentType.WEIXIN_PUB;
            }
            order.save();
        }
    }

    /**
     * 设置订单支付方式
     * @param payType
     * @param order
     */
    private static void setPaymentType(PaymentType payType , Order order) {
        if(payType != null) {
//            if(payType.equals("alipay_pc_direct")) {
//                order.paymentType = PaymentType.ALI_PC_DIRECT;
//            }
//            if(payType.equals("wx_pub")) {
//                order.paymentType = PaymentType.WEIXIN_PUB;
//            }
            order.paymentType = payType;
            order.save();
        }
    }

    /**
     * 购买成功后, 清除用户在该商户下的购物车
     * @param webUser
     * @param merchant
     */
//    private static void clearShopCart(WebUser webUser , Merchant merchant) {
//        List<ShopCart> shopCartList = ShopCart.findShopCartByUserAndMerchant(webUser , merchant.id);
//        for(ShopCart shopCart : shopCartList) {
//            shopCart.deleted = DeletedStatus.DELETED;
//            shopCart.save();
//        }
//    }

    /**
     * 发送红包
     * @param order
     */
    private static void sendShareRedBao(final Order order) {
        new Job() {
            @Override
            public void doJob() throws Exception {
                // 推荐人发送红包
                String shareCode = order.webUser.introduceCode;
                Double amount = order.merchant.redBaoAmount == null ? 1d : order.merchant.redBaoAmount;
                if(StringUtil.isNotBlank(shareCode)) {
                    WebUser shareUser = WebUser.findByIdentityCode(shareCode);
                    if(shareCode != null) {
                        RedEnvelope redEnvelope = null;
                        try {
                            redEnvelope = PingppHelper.createRejgbEnvelope(new BigDecimal(amount),order.merchant.name, shareUser.openId , order.orderNumber);
                            Logger.info("redEnvelope.STATUS : %s | BODY : %s" , redEnvelope.getStatus() , redEnvelope.getBody());
                            if(redEnvelope != null && redEnvelope.getStatus().equals("sending")){
                                new WeixinRedBao(order , shareUser , amount , "红包发送成功: 分享用户下单 获得一元红包").save();
                            } else {
                                new WeixinRedBao(order , shareUser , 0d , "红包发送失败: 发送红包时出现异常.  红包为空或 状态不是 sending").save();
                            }
                        } catch (Exception e) {
                            Logger.info("LOG 200001 payToUser : %S" , e.getMessage());
                            new WeixinRedBao(order , shareUser , 0d , "红包发送失败: " + e.getMessage()).save();
                        }
                    }
                }
            }
        }.now();

    }

    // 添加赠品
    private static void checkGiveSpecProduct(Order order) {
        Logger.info("Log 120003 Order : %s" , order);
        //判断是否有赠品
        if(order.merchant!=null && order.merchant.offeringFreebies != null &&  order.merchant.offeringFreebies ){
            Logger.info("Log 1200002  merchant  specMerchant : %s ", order.merchant);
            GiveActivitySpecProduct giveProduct = GiveActivitySpecProduct.getRandomProduct(order.amount,order.merchant.id);
            if(giveProduct != null && giveProduct.productSpecMerchant != null){
                ProductSpecMerchant specMerchant = giveProduct.productSpecMerchant ;
                Logger.info("Log 1200001  checkGiveSpecProduct  specMerchant : %s ", specMerchant.productSpec.product.name);
                // 加入 Order
                OrderItem orderItem = new  OrderItem(order,specMerchant, 0d , giveProduct.giveNum, OrderItemType.GIVE);
                orderItem.save();
                //加入 AdminOrder
                AdminOrder adminOrder = AdminOrder.findByOrder(order);
                new AdminOrderItem(orderItem , adminOrder).save();
                specMerchant.stock = specMerchant.stock - 1;
                specMerchant.save();
            }
        }
    }

    /**
     * 满赠商品
     * @param order
     */
//    private static void addLuckProduct(Order order , WeixinUser wxUser) {
//
//        List<Prize> prizeList = Prize.findByWeixinUser(wxUser , PrizeType.SHIWU , ReceiveStatus.UNRECEIVE);
//        // 赠送实物抽奖商品  然后把抽奖商品设置为 已领取
//        for(Prize prize : prizeList) {
//            Logger.info("抽奖仓库有实物商品 : %s" , prize.prizeProduct.name);
//            new OrderItem(order, prize.prizeProduct, 1 , OrderItemType.LUCK).save();
//            prize.receiveStatus = ReceiveStatus.RECEIVED;
//            prize.save();
//        }
//    }

    /**
     * 满赠商品
     * @param order
     */
//    private static void addGiveProduct(Order order , WeixinUser wxUser) {
//
////        List<Prize> prizeList = Prize.findByWeixinUser(wxUser , PrizeType.SHIWU , ReceiveStatus.UNRECEIVE);
////        // 赠送实物抽奖商品  然后把抽奖商品设置为 已领取
////        for(Prize prize : prizeList) {
////            Logger.info("抽奖仓库有实物商品 : %s" , prize.prizeProduct.name);
////            new OrderItem(order, prize.prizeProduct, 1).save();
////            prize.receiveStatus = ReceiveStatus.RECEIVED;
////            prize.save();
////        }
//
//        Date date = new Date();
//        Setting setting = Setting.all().first();
//        if(setting != null && setting.startIsGive != null && setting.endIsGive != null){
//            if(setting.startIsGive.getTime() < date.getTime() && setting.endIsGive.getTime() > date.getTime() ) {
//                List<ActivitySend> sendList = ActivitySend.findAvailable();
//                for (ActivitySend activitySend : sendList) {
////                    Logger.info("购物金额:" + order.amount + " 赠送" + activitySend.product.name + "| 赠送最小金额 : " + activitySend.minAmount + "| 赠送最大金额:" + activitySend.maxAmount);
//                        if(activitySend.prizeType == PrizeType.YOUHUIQUAN && activitySend.maxAmount > order.paymentedAmount.doubleValue() && activitySend.minAmount <= order.paymentedAmount.doubleValue() ){
////                            sendRedEnvelope(activitySend,wxUser);
//                            new WeixinRedBao(wxUser,wxUser,activitySend.amount,"购物"+order.paymentedAmount+"元返"+activitySend.amount+"元").save();
//                        }else if (activitySend.prizeType == PrizeType.SHIWU && activitySend.maxAmount > order.amount.doubleValue() && activitySend.minAmount <= order.amount.doubleValue()) {
//                            new OrderItem(order, activitySend.product, 1 , OrderItemType.GIVE).save();
//                        }
//                }
//            }
//        }
//
//
//    }
    /**
     * 添加投票奖品
     */
//    private static void addVoteProduct(Order order , WeixinUser wxUser){
//        Elector elector = Elector.findByWeiXinUser(wxUser);
//        if(elector != null && elector.isReceive == false){
//            Integer rank = elector.rank;
//            if(rank != null && rank != 0){
//                List<ActivityProduct> activityProducts = new ArrayList<ActivityProduct>();
//                if(rank == 1){
//                    activityProducts = ActivityProduct.findAvailable(ActivityType.VOTE,1);
//                    for(ActivityProduct activityProduct:activityProducts){
//                        new OrderItem(order, activityProduct.product, 1 , OrderItemType.VOTE).save();
//                    }
//                }else if(2 <= rank && rank<4){
//                    activityProducts = ActivityProduct.findAvailable(ActivityType.VOTE,2);
//                    for(ActivityProduct activityProduct:activityProducts){
//                        new OrderItem(order, activityProduct.product, 1 , OrderItemType.VOTE).save();
//                    }
//                }else if(4<=rank && rank<11){
//                    activityProducts = ActivityProduct.findAvailable(ActivityType.VOTE,3);
//                    for(ActivityProduct activityProduct:activityProducts){
//                        new OrderItem(order, activityProduct.product, 1 , OrderItemType.VOTE).save();
//                    }
//                }else if(11<=rank && rank<51){
//                    activityProducts = ActivityProduct.findAvailable(ActivityType.VOTE,4);
//                    for(ActivityProduct activityProduct:activityProducts){
//                        new OrderItem(order, activityProduct.product, 1 , OrderItemType.VOTE).save();
//                    }
//                }else if(elector.voteTimes > 50 && rank >= 51){
//                    activityProducts = ActivityProduct.findAvailable(ActivityType.VOTE,5);
//                    for(ActivityProduct activityProduct:activityProducts){
//                        new OrderItem(order, activityProduct.product, 1 , OrderItemType.VOTE).save();
//                    }
//                }
//                elector.isReceive = true;
//                elector.save();
//            }
//
//        }
//    }
    /**
     * 发送红包
     */
//    private static void sendRedEnvelope(ActivitySend activitySend,WeixinUser wxUser){
//        WeixinRedBao weixinRedBao = new WeixinRedBao(wxUser.distributor.weixinUser,wxUser,activitySend.amount,"满就返"+activitySend.amount+"元");
//        Map<String , Object> resultMap = new HashMap<>();
//        RedEnvelope redEnvelope = null;
//        String subject = "恭喜发财";
//        String body = "红包提现";
//        String description = "满就返，买得越多返的越多!";
//        String openId = "";
//        String orderNumber = "";
//        Double amount = activitySend.amount;
//
//        openId = wxUser.weixinOpenId;
//        RedBaoCashHistory redBaoCashHistory = new RedBaoCashHistory(wxUser,BigDecimal.valueOf(amount),"满就返，买得越多返的越多!");
//        orderNumber = redBaoCashHistory.id+"";
//        try {
//            redEnvelope = PingppHelper.createRejgbEnvelope(BigDecimal.valueOf(amount),subject,body,description,openId,orderNumber);
//            Logger.info("redEnvelope.STATUS : %s | BODY : %s" , redEnvelope.getStatus() , redEnvelope.getBody());
//            if(redEnvelope != null && redEnvelope.getStatus().equals("sending")){
//                WeixinRedBao.updateRedBaoStatus(wxUser,RedbaoStatus.UNUSED , RedbaoStatus.FREEZE);
//                resultMap.put("success",true);
//                resultMap.put("msg" , "恭喜发财!已通过红包发至您的账号,请查收");
//            } else {
//                redBaoCashHistory.deleted = DeletedStatus.DELETED;
//                redBaoCashHistory.content = "红包发送失败";
//                redBaoCashHistory.save();
//                resultMap.put("success",false);
//                resultMap.put("msg" , "提现失败 请与客服联系");
//            }
//        } catch (Exception e) {
//            Logger.info("LOG 200001 payToUser : %S" , e.getMessage());
//            redBaoCashHistory.deleted = DeletedStatus.DELETED;
//            redBaoCashHistory.content = e.getMessage();
//            redBaoCashHistory.save();
//            resultMap.put("success",false);
//            resultMap.put("msg" , "提现失败 请与客服联系");
//        }
//    }
    /**
     * 扣除优惠券的金额
     * @param order
     * @param wxUser
     */
//    private static void deductionWalletAmount(Order order , WeixinUser wxUser) {
//        if(order != null && order.amount != null && wxUser != null) {
//            WeixinUserWallet wallet = WeixinUserWallet.findByWeixinUser(wxUser);
//            if(wallet != null && wallet.amount != null) {
//                wallet.amount = wallet.amount.subtract(order.discountPay);
//                wallet.save();
//                new WalletHistory(wallet , order.discountPay , "购买订单:"+order.orderNumber+"。优惠金额:"+order.discountPay).save();
//            } else {
//                Logger.info("用户昵称为:%s 的钱包不存在 或者 钱包金额低于 订单优惠金额. 无法扣款. 钱包金额:%s | 优惠金额:%s" , wxUser.nickName , wallet , order.discountPay);
//            }
//        } else {
//            Logger.info("订单号为:%s 的订单信息不存在 或 订单金额金额为空 或 订单用户不存在.无法扣款" , order.orderNumber);
//        }
//    }


    /**
     * 释放该用户没有付款的订单
     */
//    private static void releaseUnPaidOrder(WebUser wxUser) {
//        List<Order> unPaidList = Order.getUnOrderByUser(wxUser.user);
//        for(Order order : unPaidList) {
//            List<OrderItem> orderItems = OrderItem.getListByOrder(order);
//            for(OrderItem oi : orderItems) {
//                Product product = OrderItem.getProductByOrderItem(oi);
//                Product.subtractRedisProduct(product , oi.buyNumber);
//            }
//            order.status = OrderStatus.CANCELED;
//            order.remark = "新订单已下单 老得订单默认取消";
//            order.save();
//        }
//    }


    //    private static void templateMessage(final Order order ,final MerchantMessage message) {
//        new Job() {
//            @Override
//            public void doJob() throws Exception {
//                if (message != null && message.weixinUser != null) {
//                    //发送支付成功通知
//                    WxMpService wxMpService = WxMpHelper.getWxMpService();
//                    WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
//                    templateMessage.setToUser(message.weixinUser.weixinOpenId);
//                    templateMessage.setTemplateId("VY2QMNf0r1jZjHI69v5D7kz59aW5aWwdqsSsgI0JIgQ");
//                    templateMessage.setUrl("http://erp.ulmsale.cn/MobileCtrl/orderSQJY?id="+orderUser.order.id);
//                    templateMessage.setTopColor("#dbdbdb");
//                    templateMessage.getDatas().add(new WxMpTemplateData("first", "您好，您有新的订单配送信息", "#173177"));
//                    templateMessage.getDatas().add(new WxMpTemplateData("order_id", orderUser.order.orderNumber, "#173177"));
//                    templateMessage.getDatas().add(new WxMpTemplateData("package_id", orderUser.order.orderNumber, "#173177"));
//                    templateMessage.getDatas().add(new WxMpTemplateData("payment_info", "客户已付款", "#173177"));
//                    templateMessage.getDatas().add(new WxMpTemplateData("carrier_info", "商品待出库", "#173177"));
//                    templateMessage.getDatas().add(new WxMpTemplateData("receiver", orderUser.name + "[" + orderUser.phone + "]" + orderUser.address, "#173177"));
//                    templateMessage.getDatas().add(new WxMpTemplateData("remark", "如有疑问，请联系我们"));
//                    try {
//                        wxMpService.templateSend(templateMessage);
//                        Logger.info("weixinCode : %s 发送模板消息成功", message.weixinUser.weixinOpenId);
//                    } catch (WxErrorException e) {
//                        Logger.info("weixinCode : %s 发送模板消息失败 . 错误原因 : %s", message.weixinUser.weixinOpenId, e.getMessage());
//                        e.printStackTrace();
//                    }
//                } else {
//                    Logger.info("weixinCode : %s 发送模板消息失败 . 错误原因 : %s 为空", new Gson().toJson(message));
//                }
//            }
//        }.now();
//    }


//    private static void templateMessage(final Order order) {
//        new Job() {
//            @Override
//            public void doJob() throws Exception {
//                //发送支付成功通知
//                WxMpService wxMpService = WxMpHelper.getWxMpService();
//                WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
//                templateMessage.setToUser(order.address.community.webUser.openId);
//                templateMessage.setTemplateId("VY2QMNf0r1jZjHI69v5D7kz59aW5aWwdqsSsgI0JIgQ-og3o");
//                templateMessage.setUrl("http://www.buhaoba.com/weixin/redEnvelope/453343");
//                templateMessage.setTopColor("#dbdbdb");
//                templateMessage.getDatas().add(new WxMpTemplateData("first", "您好，您有新的订单配送信息", "#173177"));
//                templateMessage.getDatas().add(new WxMpTemplateData("order_id", order.orderNumber , "#173177"));
//                templateMessage.getDatas().add(new WxMpTemplateData("package_id", order.orderNumber, "#173177"));
//                templateMessage.getDatas().add(new WxMpTemplateData("payment_info", "客户已付款", "#173177"));
//                templateMessage.getDatas().add(new WxMpTemplateData("carrier_info", "商品待出库", "#173177"));
//                templateMessage.getDatas().add(new WxMpTemplateData("receiver", order.name+"["+order.address.phone+"]"+order.address.address , "#173177"));
//                templateMessage.getDatas().add(new WxMpTemplateData("remark", "如有疑问，请联系我们"));
//                try {
//                    wxMpService.templateSend(templateMessage);
//                    Logger.info("weixinCode : %s 发送模板消息成功", order.address.community.webUser.openId);
//                } catch (WxErrorException e) {
//                    Logger.info("weixinCode : %s 发送模板消息失败 . 错误原因 : %s" , order.address.community.webUser.openId , e.getMessage());
//                    e.printStackTrace();
//                }
//            }
//        }.now();
//    }

//    private static void templateMessage(Order order , WeixinUser wxUser) {
//
//        //发送支付成功通知
//        WxMpService wxMpService = WxMpHelper.getWxMpService();
//        WxMpCustomMessage.WxArticle article1 = new WxMpCustomMessage.WxArticle();
//        String currentUrl = "http://" + request.host + "/weixin/order/"+order.orderNumber+"/detail/"+ order.district.linkId;
//
//        article1.setUrl(currentUrl);
////                    article1.setPicUrl("http://yijiejingwu.tunnel.mobi/public/images/huangjinli.jpg");
//        article1.setDescription("支付成功!");
//        article1.setTitle("支付成功");
//        WxMpCustomMessage message = WxMpCustomMessage.NEWS()
//                .toUser(wxUser.weixinOpenId)
//                .addArticle(article1)
//                .build();
//        try {
//            wxMpService.customMessageSend(message);
//        } catch (WxErrorException e) {
//            Logger.info("微信通知发送失败");
//            e.printStackTrace();
//        }
//    }


}
